package br.com.tas;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import br.com.tas.dao.CoordinatesDao;
import br.com.tas.dao.interfaces.ICoordinatesDao;
import br.com.tas.exception.DataException;
import br.com.tas.model.CoordinatesBean;

import com.example.tas.R;
import com.google.android.maps.GeoPoint;

public class CoordinatesActivity extends Activity {
	
	private ICoordinatesDao coordinatesDao;
	private CoordinatesBean coordinates;
	
	LayoutInflater factory;
	List<Address> fromLocationName = null;
	Address a;
	View dialog_address;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		coordinatesDao = new CoordinatesDao(this);
		setContentView(R.layout.activity_coordinates);
				
		factory = LayoutInflater.from(this);
		
		Button address = (Button) findViewById(R.id.buttonAddress);
		Button location = (Button) findViewById(R.id.buttonLocation);
		
		fillCoordinates();
		
		address.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) 
            {   
            	addressDialog();
            }});
		
		location.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) 
            {   
//                startActivity(new Intent(CoordinatesActivity.this, MyMapLocationActivity.class));
            }});
	}
	
	public void addressDialog() {
		dialog_address = factory.inflate(R.layout.dialog_address, null);
		
		((EditText) dialog_address.findViewById(R.id.edt_profile)).setText(coordinates.getProfile());
		
		if (coordinates.getAddress() != null) {
	    	((EditText) dialog_address.findViewById(R.id.edt_address)).setText(String.valueOf(coordinates.getAddress()));
		}
    	AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
				this);
		alertDialogBuilder.setTitle(R.string.title_address)
		.setView(dialog_address);
		alertDialogBuilder.setCancelable(false)
		.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				if(validate()){
					geoCoder();
				}
			}
		  })
		.setNegativeButton(R.string.button_cancel,null);

		alertDialogBuilder.create().show();
	}
	
	private void fillCoordinates() {
		Bundle bundle = getIntent().getExtras();
        
        if (bundle != null) {
        	coordinates = (CoordinatesBean)bundle.getSerializable("coordinates");   	
        } else{
        	coordinates = new CoordinatesBean();
        }
    }
	
	private void save() {
		String profile = ((EditText) dialog_address.findViewById(R.id.edt_profile)).getText().toString();
		coordinates.setProfile(profile);
		coordinates.setAddress(String.valueOf(a.getAddressLine(0)));
		coordinates.setLatitude(String.valueOf(a.getLatitude()));
		coordinates.setLongitude(String.valueOf(a.getLongitude()));    	

    		try {
    			coordinatesDao.save(coordinates);
				
    			if(coordinatesDao.findAll(new CoordinatesBean()).size() == 1) {
    				startActivity(new Intent(this, ListCoordinatesActivity.class));
    			} else {
    				finish();
    			}
			} catch (DataException e) {
				Toast.makeText(this, getString(R.string.error_save_coordinates), Toast.LENGTH_SHORT ).show();
			}
    }
	
	public void geoCoder() {
		Geocoder geoCoder = new Geocoder(getApplicationContext(),
				Locale.getDefault());
		String textToSearch = ((EditText) dialog_address.findViewById(R.id.edt_address)).getText().toString();

		try {
			fromLocationName = geoCoder.getFromLocationName(textToSearch, 1);
			
			if (fromLocationName != null && fromLocationName.size() > 0) {
				a = fromLocationName.get(0);
				new GeoPoint((int) (a.getLatitude() * 1E6),
						(int) (a.getLongitude() * 1E6));
			}
			save();
		} catch (IOException e) {
			e.printStackTrace();
			Toast.makeText(CoordinatesActivity.this, R.string.error_network_io,
				    Toast.LENGTH_LONG).show();
		}			
	}
	
	private boolean validate() {
		EditText profile = ((EditText) dialog_address.findViewById(R.id.edt_profile));
		EditText address = ((EditText) dialog_address.findViewById(R.id.edt_address));
		
		if (address.getText() == null || !(address.getText().length() > 0)){
    		Toast.makeText(this, getString(R.string.msg_address_not_null), Toast.LENGTH_SHORT ).show();
    		return false;
    	} else if (profile.getText() == null || !(profile.getText().length() > 0)){
    		Toast.makeText(this, getString(R.string.msg_profile_not_null), Toast.LENGTH_SHORT ).show();
    		return false;
    	}
    	
		return true;
    }
}
